<script setup>
import { listMapData, listBoundaryData } from '@/api/data'
import { ref, onMounted } from 'vue'
const MapDataList = ref([])
var map = ''
const emit = defineEmits(['openPopup'])
onMounted(() => {
  getList()
})
// 添加标记
function addMarker(markerInfo) {
  //创建图片对象
  const position = markerInfo.position.split(',')
  var e = {
    lng: parseFloat(position[0]),
    lat: parseFloat(position[1]),
  }

  var icon = new T.Icon(selectIcon(markerInfo.color))
  //向地图上添加自定义标注
  var marker = new T.Marker(new T.LngLat(e.lng, e.lat), {
    icon: icon,
    zIndexOffset: 0,
  })
  marker.addEventListener('click', (e) => {
    emit('openPopup', markerInfo)
  })
  var label = new T.Label({
    text: `<p>${markerInfo.title}</p>`,
    position: new T.LngLat(e.lng, e.lat),
    offset: selectOffset(markerInfo.color),
  })
  label.setFontSize(16)
  label.setFontColor('white')
  label.setBackgroundColor('transparent')
  label.setBorderLine(0)
  // label.setBorderColor("none")
  map.addOverLay(marker)
  map.addOverLay(label)
}
// 选择图片
function selectImage(color) {
  switch (color) {
    case 'yellow':
      return 'https://ddns.ideal2077.com:5555/d/Handsomedog/shiliang/icon%20(2).png?sign=blt6bGAbCEu4eV1CV77jb0eFhUaDWRpiTrQy9v9kMzs=:0'
    case 'green':
      return 'https://ddns.ideal2077.com:5555/d/Handsomedog/shiliang/icon%20(3).png?sign=QgZmuKGt52ltFC0-3EKHG_oC0fgIaR_kYJt239Q9Fn4=:0'
    case 'blue':
      return 'https://ddns.ideal2077.com:5555/d/Handsomedog/shiliang/icon%20(1).png?sign=JZ5_f4AYa3GSK87HtYc85xyXz42KvrTH7tXm6gStyWA=:0'
    default:
      return 'https://ddns.ideal2077.com:5555/d/Handsomedog/shiliang/icon%20(2).png?sign=blt6bGAbCEu4eV1CV77jb0eFhUaDWRpiTrQy9v9kMzs=:0'
  }
}
// 选择图标
function selectIcon(color) {
  switch (color) {
    case 'yellow':
      return {
        iconUrl: selectImage(color),
        iconSize: new T.Point(150, 55),
        iconAnchor: new T.Point(30, 50),
      }
    case 'green':
      return {
        iconUrl: selectImage(color),
        iconSize: new T.Point(150, 55),
        iconAnchor: new T.Point(20, 58),
      }
    case 'blue':
      return {
        iconUrl: selectImage(color),
        iconSize: new T.Point(130, 65),
        iconAnchor: new T.Point(30, 60),
      }
    default:
      return {
        iconUrl: selectImage(color),
        iconSize: new T.Point(150, 55),
        iconAnchor: new T.Point(30, 50),
      }
  }
}
// 选择文字偏差
function selectOffset(color) {
  switch (color) {
    case 'yellow':
      return new T.Point(10, -23)
    case 'green':
      return new T.Point(5, -28)
    case 'blue':
      return new T.Point(0, -21)
    default:
      return new T.Point(10, -23)
  }
}
/** 查询地图列表 */
function getList() {
  listMapData().then((response) => {
    MapDataList.value = response.rows
    MapDataList.value = MapDataList.value.slice(1)
    var zoom = 13
    const center = response.rows[0].position.split(',')
    const position = {
      lng: parseFloat(center[0]),
      lat: parseFloat(center[1]),
    }
    map = new T.Map('mapDiv')
    map.centerAndZoom(new T.LngLat(position.lng, position.lat), zoom)
    const imageURL =
      'http://t0.tianditu.gov.cn/img_w/wmts?' +
      'SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles' +
      '&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=8bce5ceb483255b37a4aaa52bc86d11e'
    const imageURLT =
      'http://t0.tianditu.gov.cn/cia_w/wmts?' +
      'SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles' +
      '&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}' +
      '&tk=8bce5ceb483255b37a4aaa52bc86d11e'
    //创建自定义图层对象
    var lay = new T.TileLayer(imageURL, { minZoom: 1, maxZoom: 18 })
    var textLayer = new T.TileLayer(imageURLT, {
      minZoom: 1,
      maxZoom: 18,
    })
    //将图层增加到地图上
    map.addLayer(lay)
    map.addLayer(textLayer)
    function loadGeoJson() {
      var countries = []
      var countriesOverlay = new T.D3Overlay(init, redraw)
      d3.json(
        'https://ddns.ideal2077.com:5555/d/Handsomedog/shiliang/%E7%9F%B3%E6%A2%81%E9%95%87.geojson?sign=tqAPonliYDiMECn1umfHzl88RGiZMsxs_9MPGRfjbSs=:0',
        function (data) {
          countries = data.features
          map.addOverLay(countriesOverlay)
          countriesOverlay.bringToBack()
        },
      )
      function init(sel, transform) {
        var upd = sel.selectAll('path.geojson').data(countries)
        upd
          .enter()
          .append('path')
          .attr('class', 'geojson')
          .attr('stroke', 'black')
          .attr('fill', function (d, i) {
            return d3.hsl(Math.random() * 360, 0.9, 0.5)
          })
          .attr('fill-opacity', '0.5')
      }

      function redraw(sel, transform) {
        sel.selectAll('path.geojson').each(function (d, i) {
          d3.select(this).attr('d', transform.pathFromGeojson)
        })
      }
    }
    loadGeoJson()
    for (let i = 0; i < MapDataList.value.length; i++) {
      addMarker(MapDataList.value[i])
    }
    listBoundaryData({
      pageNum: 1,
      pageSize: 1000,
    }).then((response) => {
      const data = response.rows
      for (let i = 0; i < data.length; i++) {
        const item = data[i]
        const points = JSON.parse(item.position)
        const polygon = new T.Polygon(points, {
          color: item.color,
          weight: item.weight,
          opacity: item.opacity,
          fillColor: item.fillColor,
          fillOpacity: item.fillOpacity,
        })
        map.addOverLay(polygon)
      }
    })
  })
}
</script>
<template>
  <div id="mapDiv"></div>
</template>
<style lang="scss" scoped>
#mapDiv {
  width: 100%;
  height: 100%;
  pointer-events: auto;
}
.two {
  display: grid;
  grid-template-columns: 50% 50%;
  .list {
    margin-bottom: 20px;
  }
}
.position {
  display: flex;
  justify-content: center;
}
:deep(.tdt-label) {
  font-style: italic;
}
.color-preview {
  width: 100%;
  height: 40px;
  margin-top: 10px;
  img {
    height: 100%;
  }
}
</style>
